

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" href="/img/favicon.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="Cheney">
  <meta name="keywords" content="Coding">
  
    <meta name="description" content="随着电子技术的迅速发展,人们使用便携数码设备(如手机、相机等)获取花卉图像越来越方便,如何自动识别花卉种类受到了广泛的关注。由于花卉所处背景的复杂性,以及花卉自身的类间相似性和类内多样性,利用传统的手工提取特征进行图像分类的方法,并不能很好地解决花卉图像分类这一问题。">
<meta property="og:type" content="article">
<meta property="og:title" content="花卉识别(tensorflow)">
<meta property="og:url" content="https://cheney822.gitee.io/2021/10/02/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD__%E8%8A%B1%E5%8D%89%E8%AF%86%E5%88%AB(tensorflow)/index.html">
<meta property="og:site_name" content="Cheney blog">
<meta property="og:description" content="随着电子技术的迅速发展,人们使用便携数码设备(如手机、相机等)获取花卉图像越来越方便,如何自动识别花卉种类受到了广泛的关注。由于花卉所处背景的复杂性,以及花卉自身的类间相似性和类内多样性,利用传统的手工提取特征进行图像分类的方法,并不能很好地解决花卉图像分类这一问题。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://imgbed.cheney.cc/picgo/abc4f1a34839420d9532fc626fcddf43.png">
<meta property="og:image" content="https://imgbed.cheney.cc/picgo/672358d2d38a4369b01b86bdb6e4b83d.png">
<meta property="og:image" content="https://imgbed.cheney.cc/picgo/9c3a5a7efee943c58315680447c94d36.png">
<meta property="og:image" content="https://imgbed.cheney.cc/picgo/9faf0e491c744338b2a6b189503f4a7c.png">
<meta property="og:image" content="https://imgbed.cheney.cc/picgo/b210ddc9555844f0b07c486f1bf02216.png">
<meta property="og:image" content="https://imgbed.cheney.cc/picgo/ff6d7640f4a242c5a9c3668fa7b61667.png">
<meta property="og:image" content="https://imgbed.cheney.cc/picgo/e957a9e3b89d4b5e8cc7d94dfd8db10f.png">
<meta property="og:image" content="https://imgbed.cheney.cc/picgo/9f8740bbe4fb48dfa9a20053bc8b8925.png">
<meta property="article:published_time" content="2021-10-02T05:14:00.000Z">
<meta property="article:modified_time" content="2022-04-05T13:14:31.227Z">
<meta property="article:author" content="Cheney">
<meta property="article:tag" content="Python">
<meta property="article:tag" content="Tensorflow">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://imgbed.cheney.cc/picgo/abc4f1a34839420d9532fc626fcddf43.png">
  
  
  <title>花卉识别(tensorflow) - Cheney blog</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4/github-markdown.min.css" />
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hint.css@2/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css" />
  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"cheney822.gitee.io","root":"/","version":"1.8.14","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":1},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.4.1"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>Cheney Blog</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('https://imgbed.cheney.cc/Blog_config/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="花卉识别(tensorflow)">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2021-10-02 13:14" pubdate>
        2021年10月2日 下午
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      7.9k 字
    </span>
  

  
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      40 分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">花卉识别(tensorflow)</h1>
            
            <div class="markdown-body">
              <blockquote>
<p>参考教材：人工智能导论(第4版) 王万良 高等教育出版社<br>实验环境：Python3.6 + Tensor flow 1.12 </p>
</blockquote>
<p><kbd> ==人工智能导论实验导航== </kbd></p>
<p>==实验一：斑马问题== <a target="_blank" rel="noopener" href="https://blog.csdn.net/weixin_46291251/article/details/122246347">https://blog.csdn.net/weixin_46291251/article/details/122246347</a></p>
<p>==实验二：图像恢复== <a target="_blank" rel="noopener" href="https://blog.csdn.net/weixin_46291251/article/details/122561220">https://blog.csdn.net/weixin_46291251/article/details/122561220</a></p>
<p>==实验三：花卉识别== <a target="_blank" rel="noopener" href="https://blog.csdn.net/weixin_46291251/article/details/122561505">https://blog.csdn.net/weixin_46291251/article/details/122561505</a></p>
<p>==实验四：手写体生成== <a target="_blank" rel="noopener" href="https://blog.csdn.net/weixin_46291251/article/details/122576478">https://blog.csdn.net/weixin_46291251/article/details/122576478</a></p>
<p>==实验源码：== xxx</p>
<h1 id="3-1实验介绍"><a href="#3-1实验介绍" class="headerlink" title="3.1实验介绍"></a>3.1实验介绍</h1><h2 id="3-1-1实验背景"><a href="#3-1-1实验背景" class="headerlink" title="3.1.1实验背景"></a>3.1.1实验背景</h2><p>深度学习为人工智能核心技术，本章主要围绕深度学习涉及的全连接神经网络、卷积神经网络和对抗神经网络而开设的实验。<br>卷积神经网络（Convolutional Neural Networks, CNN）是一类包含卷积计算且具有深度结构的前馈神经网络（Feedforward Neural Networks），是深度学习（deep learning）的代表算法之一 。卷积神经网络具有表征学习（representation learning）能力，能够按其阶层结构对输入信息进行平移不变分类（shift-invariant classification）</p>
<h2 id="3-1-2实验目的"><a href="#3-1-2实验目的" class="headerlink" title="3.1.2实验目的"></a>3.1.2实验目的</h2><p>本章实验的主要目的是掌握深度学习相关基础知识点，了解深度学习相关基础知识，经典全连接神经网络、卷积神经网络和对抗神经网络。掌握不同神经网络架构的设计原理，熟悉使用Tensorflow 2.1深度学习框架实现深度学习实验的一般流程。</p>
<h2 id="3-1-3实验简介"><a href="#3-1-3实验简介" class="headerlink" title="3.1.3实验简介"></a>3.1.3实验简介</h2><p>随着电子技术的迅速发展,人们使用便携数码设备(如手机、相机等)获取花卉图像越来越方便,如何自动识别花卉种类受到了广泛的关注。由于花卉所处背景的复杂性,以及花卉自身的类间相似性和类内多样性,利用传统的手工提取特征进行图像分类的方法,并不能很好地解决花卉图像分类这一问题。<img src="https://imgbed.cheney.cc/picgo/abc4f1a34839420d9532fc626fcddf43.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p>本实验基于卷积神经网络实现的花卉识别实验与传统图像分类方法不同,卷积神经网络无需人工提取特征,可以根据输入图像,自动学习包含丰富语义信息的特征,得到更为全面的花卉图像特征描述,可以很好地表达图像不同类别的信息。</p>
<h1 id="3-2概要设计"><a href="#3-2概要设计" class="headerlink" title="3.2概要设计"></a>3.2概要设计</h1><p>本实验将用户在客户端选取的花卉图像作为输入，运行花卉识别模型，实时返回识别结果作为输出结果并显示给用户。</p>
<h2 id="3-2-1功能结构"><a href="#3-2-1功能结构" class="headerlink" title="3.2.1功能结构"></a>3.2.1功能结构</h2><p>花卉识别实验总体设计如下图所示，该实验可以划分为数据处理、模型构建、图像识别三个主要的子实验。<br>其中数据处理子实验包括数据集划分、图像预处理两个部分；<br>模型构建子实验主要包括模型定义、模型训练以及模型部署三个部分；<br>图像识别子实验内容主要包括读取花卉图像、运行推断模型进行图像特征提取，输出模型识别结果三个部分。<img src="https://imgbed.cheney.cc/picgo/672358d2d38a4369b01b86bdb6e4b83d.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<h2 id="3-2-2体系结构"><a href="#3-2-2体系结构" class="headerlink" title="3.2.2体系结构"></a>3.2.2体系结构</h2><p>按照体系结构划分，整个实验的体系结构可以划分为三部分，分别为模型训练、模型保存和模型推理，如图5-3所示。各层侧重点各不相同。<br>训练层运行在安装有tensorflow框架的服务器，最好配置计算加速卡。<br>推断层运行于开发环境，能够支持卷积神经网络的加速。<br>展示层运行于客户端应用程序，能够完成图像选择并实时显示推断层的计算结果。<br>各层之间存在单向依赖关系。推断层需要的网络模型由训练层提供，并根据需要进行必要的格式转换或加速重构。相应的，展示层要显示的元数据需要由推断层计算得到。<br><img src="https://imgbed.cheney.cc/picgo/9c3a5a7efee943c58315680447c94d36.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<h1 id="3-3详细设计"><a href="#3-3详细设计" class="headerlink" title="3.3详细设计"></a>3.3详细设计</h1><h2 id="3-3-1导入实验环境"><a href="#3-3-1导入实验环境" class="headerlink" title="3.3.1导入实验环境"></a>3.3.1导入实验环境</h2><h3 id="步骤-1导入相应的模块"><a href="#步骤-1导入相应的模块" class="headerlink" title="步骤 1导入相应的模块"></a>步骤 1导入相应的模块</h3><p>skimage包主要用于图像数据的处理，在该实验当中， io模块主要用于图像数据的读取（imread）和输出（imshow）操作，transform模块主要用于改变图像的大小（resize函数）；<br>glob包主要用于查找符合特定规则的文件路径名，跟使用windows下的文件搜索相似；<br>os模块主要用于处理文件和目录，比如：获取当前目录下文件，删除制定文件，改变目录，查看文件大小等；<br>tensorflow是目前业界最流行的深度学习框架之一，在图像，语音，文本，目标检测等领域都有深入的应用，也是该实验的核心，主要用于定义占位符，定义变量，创建卷积神经网络模型；numpy是一个基于python的科学计算包，在该实验中主要用来处理数值运算；<br>time模块主要用于处理时间系列的数据，在该实验主要用于返回当前时间戳，计算脚本每个epoch运行所需要的时间。</p>
<figure class="highlight python"><table><tr><td class="gutter"><div class="code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></div></td><td class="code"><pre><code class="hljs python"><span class="hljs-comment"># 导入模块</span><br><span class="hljs-comment"># -*- coding:uft-8</span><br><span class="hljs-comment">#from  skimage  </span><br><span class="hljs-keyword">import</span> glob<br><span class="hljs-keyword">import</span> os<br><span class="hljs-keyword">import</span> cv2<br><span class="hljs-keyword">import</span>  tensorflow <span class="hljs-keyword">as</span> tf<br><span class="hljs-keyword">from</span> tensorflow.keras <span class="hljs-keyword">import</span> layers, optimizers, datasets, Sequential<br><span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np<br><span class="hljs-keyword">import</span> matplotlib.pyplot <span class="hljs-keyword">as</span> plt<br><span class="hljs-keyword">from</span> sklearn.model_selection <span class="hljs-keyword">import</span> train_test_split<br></code></pre></td></tr></table></figure>

<h3 id="步骤-2设置初始化环境"><a href="#步骤-2设置初始化环境" class="headerlink" title="步骤 2设置初始化环境"></a>步骤 2设置初始化环境</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-comment"># 数据集的地址，改为自己的图片文件地址</span><br>path = <span class="hljs-string">&#x27;./flower_photos/&#x27;</span><br><span class="hljs-comment"># 缩放图片大小为100*100，C为通道，彩色图片数值为3</span><br>w = <span class="hljs-number">100</span><br>h = <span class="hljs-number">100</span><br>c = <span class="hljs-number">3</span><br><br>types = <span class="hljs-number">0</span>  <span class="hljs-comment"># 所有花的种类数,也是标签的个数</span><br>flower = &#123;<span class="hljs-number">0</span>: <span class="hljs-string">&#x27;bee&#x27;</span>, <span class="hljs-number">1</span>: <span class="hljs-string">&#x27;blackberry&#x27;</span>, <span class="hljs-number">2</span>: <span class="hljs-string">&#x27;blanket&#x27;</span>, <span class="hljs-number">3</span>: <span class="hljs-string">&#x27;bougainvillea&#x27;</span>, <span class="hljs-number">4</span>: <span class="hljs-string">&#x27;bromelia&#x27;</span>, <span class="hljs-number">5</span>: <span class="hljs-string">&#x27;foxglove&#x27;</span>&#125;<br></code></pre></td></tr></table></figure>



<h2 id="3-3-2数据准备"><a href="#3-3-2数据准备" class="headerlink" title="3.3.2数据准备"></a>3.3.2数据准备</h2><p>这里通过os.listdir判断给定目录下的是文件还是文件夹，如果是文件夹，那么就进入读取其中的所有文件，这些图像对应的标签就是他们所属的文件夹的编号，遍历完所有子文件夹(这里不限制文件夹数目，可以动态的识别出文件夹)之后便完成了数据集的读取，函数返回读取到的所有图片和图片对应的标签。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-comment"># 读取图片</span><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">read_img</span>(<span class="hljs-params">path</span>):<br>    <span class="hljs-keyword">global</span> types<br>    <span class="hljs-keyword">global</span> flower<br>    imgs = []<br>    labels = []<br>    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> os.path.isdir(path):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;路径不正确&quot;</span>)<br>        exit(<span class="hljs-number">0</span>)<br><br>    <span class="hljs-keyword">for</span> s <span class="hljs-keyword">in</span> os.listdir(path):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;\nfolder  &quot;</span>, s)<br>        f_label = s.split(<span class="hljs-string">&quot;_&quot;</span>)[-<span class="hljs-number">1</span>]<br>        flower[types] = s.split(<span class="hljs-string">&quot;_&quot;</span>)[<span class="hljs-number">0</span>]<br>        <span class="hljs-comment"># flower[f_label]=s.split(&quot;_&quot;)[0]</span><br><br>        s = path + s + <span class="hljs-string">&quot;/&quot;</span><br>        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> os.path.isdir(s):  <span class="hljs-comment"># 只读文件夹</span><br>            <span class="hljs-keyword">continue</span><br><br>        types += <span class="hljs-number">1</span>  <span class="hljs-comment"># 数据集数目加1</span><br><br>        <span class="hljs-keyword">for</span> im <span class="hljs-keyword">in</span> os.listdir(s):<br>            im = s + im<br>            <span class="hljs-built_in">print</span>(<span class="hljs-string">&#x27;\r\tloading :%s&#x27;</span> % (im), end=<span class="hljs-string">&quot;&quot;</span>)<br>            img = io.imread(im)<br>            img = transform.resize(img, (w, h))<br>            imgs.append(img)<br>            <span class="hljs-comment"># labels.append(f_label)</span><br>            labels.append(types - <span class="hljs-number">1</span>)<br><br>    <span class="hljs-keyword">return</span> np.asarray(imgs, np.float32), np.asarray(labels, np.int32)<br></code></pre></td></tr></table></figure>



<h2 id="3-3-3构建花卉识别模型"><a href="#3-3-3构建花卉识别模型" class="headerlink" title="3.3.3构建花卉识别模型"></a>3.3.3构建花卉识别模型</h2><p>CNN训练模型<br>       模型尺寸分析：卷积层全都采用了补0，所以经过卷积层长和宽不变，只有深度加深。池化层全都没有补0，所以经过池化层长和宽均减小，深度不变。<br>       模型尺寸变化：100×100×3-&gt;100×100×32-&gt;50×50×32-&gt;50×50×64-&gt;25×25×64-&gt;25×25×128-&gt;12×12×128-&gt;12×12×128-&gt;6×6×128<br>                  本文的CNN模型比较简单，后续完全可以通过增大模型复杂度或者改参数调试以及对图像进行预处理来提高准确率。</p>
<p>下面列出网络模型的部分：<br>这里首先用tf.getvariable创建新的tensorflow变量并用tf.tf.constant_initializer<br>和tf.constant_initializer初始化为(stddev=0.1)和（0.0）<br>然后用 tf.nn.conv2d创建2维卷积层步长参数为[1,1,1,1]，卷积方式为’SAME’<br>然后用线性整流函数relu进行处理</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">with</span> tf.variable_scope(<span class="hljs-string">&#x27;layer1-conv1&#x27;</span>):<br>     conv1_weights = 			tf.get_variable(<span class="hljs-string">&quot;weight&quot;</span>,[<span class="hljs-number">5</span>,<span class="hljs-number">5</span>,<span class="hljs-number">3</span>,<span class="hljs-number">32</span>],initializer=tf.truncated_normal_initializer(stddev=<span class="hljs-number">0.1</span>))<br>     conv1_biases = tf.get_variable(<span class="hljs-string">&quot;bias&quot;</span>, [<span class="hljs-number">32</span>], initializer=tf.constant_initializer(<span class="hljs-number">0.0</span>))<br>     conv1 = tf.nn.conv2d(input_tensor, conv1_weights, strides=[<span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>], padding=<span class="hljs-string">&#x27;SAME&#x27;</span>)<br>     relu1 = tf.nn.relu(tf.nn.bias_add(conv1, conv1_biases))<br></code></pre></td></tr></table></figure>
<p>下面类似：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">with</span> tf.variable_scope(<span class="hljs-string">&#x27;layer11-fc3&#x27;</span>):<br>        fc3_weights = tf.get_variable(<span class="hljs-string">&quot;weight&quot;</span>, [<span class="hljs-number">512</span>, <span class="hljs-number">5</span>],<br>                                      initializer=tf.truncated_normal_initializer(stddev=<span class="hljs-number">0.1</span>))<br>        <span class="hljs-keyword">if</span> regularizer != <span class="hljs-literal">None</span>: tf.add_to_collection(<span class="hljs-string">&#x27;losses&#x27;</span>, regularizer(fc3_weights))<br>        fc3_biases = tf.get_variable(<span class="hljs-string">&quot;bias&quot;</span>, [<span class="hljs-number">5</span>], initializer=tf.constant_initializer(<span class="hljs-number">0.1</span>))<br>        logit = tf.matmul(fc2, fc3_weights) + fc3_biases<br></code></pre></td></tr></table></figure>


<p>下面是池化操作：利用tf.nn.max_pool完成，池化窗口大小为[1,2,2,1]，填充方式为VALID表示不填充，窗口在每一个维度上滑动的步长为[1,2,2,1]</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">with</span> tf.name_scope(<span class="hljs-string">&quot;layer4-pool2&quot;</span>):<br>        pool2 = tf.nn.max_pool(relu2, ksize=[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">2</span>, <span class="hljs-number">1</span>], strides=[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">2</span>, <span class="hljs-number">1</span>], padding=<span class="hljs-string">&#x27;VALID&#x27;</span>)<br></code></pre></td></tr></table></figure>



<h2 id="3-3-4训练并保存模型"><a href="#3-3-4训练并保存模型" class="headerlink" title="3.3.4训练并保存模型"></a>3.3.4训练并保存模型</h2><p>下面给出部分训练模型的代码：</p>
<p>训练过程中输出每一次训练的train loss 、train acc、val loss、val acc用于分析训练的效果。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">train</span>():<br>......<br>    <span class="hljs-keyword">for</span> epoch <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(n_epoch):<br>        start_time = time.time()<br><br>        <span class="hljs-comment"># training</span><br>        train_loss, train_acc, n_batch = <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span><br>        <span class="hljs-keyword">for</span> x_train_a, y_train_a <span class="hljs-keyword">in</span> minibatches(x_train, y_train, batch_size, shuffle=<span class="hljs-literal">True</span>):<br>            _, err, ac = sess.run([train_op, loss, acc], feed_dict=&#123;x: x_train_a, y_: y_train_a&#125;)<br>            train_loss += err<br>            train_acc += ac<br>            n_batch += <span class="hljs-number">1</span><br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;--第&quot;</span>+<span class="hljs-built_in">str</span>(epoch + <span class="hljs-number">1</span>)+<span class="hljs-string">&quot;次训练:&quot;</span>.ljust(<span class="hljs-number">10</span>, <span class="hljs-string">&quot; &quot;</span>), end=<span class="hljs-string">&quot;&quot;</span>)<br>        <span class="hljs-built_in">print</span>(<span class="hljs-built_in">str</span>((np.<span class="hljs-built_in">sum</span>(train_loss)) / n_batch).ljust(<span class="hljs-number">20</span>, <span class="hljs-string">&quot; &quot;</span>), (<span class="hljs-built_in">str</span>(np.<span class="hljs-built_in">sum</span>(train_acc) / n_batch)).ljust(<span class="hljs-number">20</span>, <span class="hljs-string">&quot; &quot;</span>), end=<span class="hljs-string">&quot;&quot;</span>)<br><br>        <span class="hljs-comment"># validation</span><br>        val_loss, val_acc, n_batch = <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span><br>        <span class="hljs-keyword">for</span> x_val_a, y_val_a <span class="hljs-keyword">in</span> minibatches(x_val, y_val, batch_size, shuffle=<span class="hljs-literal">False</span>):<br>            err, ac = sess.run([loss, acc], feed_dict=&#123;x: x_val_a, y_: y_val_a&#125;)<br>            val_loss += err<br>            val_acc += ac<br>            n_batch += <span class="hljs-number">1</span><br>        <span class="hljs-built_in">print</span>(<span class="hljs-built_in">str</span>((np.<span class="hljs-built_in">sum</span>(val_loss) / n_batch)).ljust(<span class="hljs-number">20</span>, <span class="hljs-string">&quot; &quot;</span>), <span class="hljs-built_in">str</span>((np.<span class="hljs-built_in">sum</span>(val_acc) / n_batch)).ljust(<span class="hljs-number">20</span>, <span class="hljs-string">&quot; &quot;</span>))<br></code></pre></td></tr></table></figure>



<h2 id="3-3-5识别花卉"><a href="#3-3-5识别花卉" class="headerlink" title="3.3.5识别花卉"></a>3.3.5识别花卉</h2><p>首先创建用于读取测试的花卉图片的函数，该函数读取测试文件夹中的所有图片并以np.array的形式返回。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">get_test_img</span>(<span class="hljs-params">path</span>):<br>    imgs = []<br>    cv_data = []<br>    <span class="hljs-keyword">for</span> im <span class="hljs-keyword">in</span> os.listdir(path):<br>        im = path + im<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&#x27;\rrecognizing :%s&#x27;</span> % (im), end=<span class="hljs-string">&quot;&quot;</span>)<br>        img = io.imread(im)<br>        img = transform.resize(img, (w, h))<br>        imgs.append(img)<br>        cv_data.append(cv2.imread(im))<br>    <span class="hljs-keyword">return</span> np.asarray(imgs), cv_data<br></code></pre></td></tr></table></figure>

<p>然后就可以利用上述训练得到的判别器来判断所给的图像的标签。然后就可以根据得到的标签输出花的名字</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">recog</span>():<br>    path = <span class="hljs-string">&#x27;./data/TestImages/&#x27;</span><br>    model_path = <span class="hljs-string">&quot;./model/&quot;</span><br><br>    data, cv_datas = get_test_img(path)<br>    <span class="hljs-keyword">with</span> tf.Session() <span class="hljs-keyword">as</span> sess:<br>        saver = tf.train.import_meta_graph(model_path + <span class="hljs-string">&#x27;model.ckpt.meta&#x27;</span>)<br>        saver.restore(sess, tf.train.latest_checkpoint(model_path))<br><br>        graph = tf.get_default_graph()<br>        x = graph.get_tensor_by_name(<span class="hljs-string">&quot;x:0&quot;</span>)<br>        feed_dict = &#123;x: data&#125;<br><br>        logits = graph.get_tensor_by_name(<span class="hljs-string">&quot;logits_eval:0&quot;</span>)<br>        classification_result = sess.run(logits, feed_dict)<br><br>        <span class="hljs-comment"># 打印出预测矩阵</span><br>        <span class="hljs-built_in">print</span>(classification_result)<br>        <span class="hljs-comment"># 打印出预测矩阵每一行最大值的索引</span><br>        <span class="hljs-built_in">print</span>(tf.argmax(classification_result, <span class="hljs-number">1</span>).<span class="hljs-built_in">eval</span>())<br>        <span class="hljs-comment"># 根据索引通过字典对应花的分类</span><br>        output = tf.argmax(classification_result, <span class="hljs-number">1</span>).<span class="hljs-built_in">eval</span>()<br>        <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-built_in">len</span>(output)):<br>            <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;第&quot;</span>, i + <span class="hljs-number">1</span>, <span class="hljs-string">&quot;朵花预测: label:&quot;</span>, output[i], <span class="hljs-string">&quot;\t&quot;</span>, flower[output[i]])<br>            font = cv2.FONT_HERSHEY_SIMPLEX<br>            img = cv_datas[i]<br>            cv2.putText(img, flower[output[i]], (<span class="hljs-number">20</span>, <span class="hljs-number">20</span>), font, <span class="hljs-number">1</span>, (<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>), <span class="hljs-number">1</span>)<br>            <span class="hljs-comment"># cv2.imshow(flower[output[i]],img)</span><br>            <span class="hljs-comment"># cv2.waitKey(0)  # # 使图片停留用于观察，没有这一行代码，图片会在展示瞬间后消失</span><br></code></pre></td></tr></table></figure>

<p>由于待识别的图片一共有六张，所以将其排列在一个两行三列的图片之中。<br>使用pyplot的subplot即可实现，遍历所有图片并分别将图片放第i个位置处。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs python">        <span class="hljs-comment"># 下面改用pyplot绘图以让结果显示在一张图片中</span><br>        pyplot.subplot(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">1</span> + i)  <span class="hljs-comment"># 使用subplot()构建子图，第一个参数5表示每列有5张图，第二个参数表示每行有6张图，1+i表示第(1+i张图)</span><br>        pyplot.axis(<span class="hljs-string">&#x27;off&#x27;</span>)  <span class="hljs-comment"># 关闭坐标轴(&quot;on&quot;为显示坐标轴)</span><br>        pyplot.title(flower[output[i]])<br>        pyplot.imshow(img, cmap=<span class="hljs-string">&#x27;gray_r&#x27;</span>)  <span class="hljs-comment"># 使用imshow()函数画出训练集相应图片原始像素数据，参数cmap = gray表示黑底白字图像，这边使用&quot;gray_r&quot;表示白底黑字图</span><br>pyplot.savefig(<span class="hljs-string">&#x27;res.png&#x27;</span>)  <span class="hljs-comment"># 保存图片</span><br>pyplot.show()<br></code></pre></td></tr></table></figure>

<h1 id="3-4运行测试"><a href="#3-4运行测试" class="headerlink" title="3.4运行测试"></a>3.4运行测试</h1><p>首先读取数据集，由下图可见，程序依次读取了六个文件夹，并从每个文件夹中读取了多张图片。<img src="https://imgbed.cheney.cc/picgo/9faf0e491c744338b2a6b189503f4a7c.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p>然后开始训练，这里输出了：训练集损失值、:训练集准确率、测试集损失值、测试集准确率这几个指标，通过观察数值变化可以发现：<br>train loss不断减小<br>Train acc不断增大直至为1并稳定为1<br>Val loss  大体上不断减小，但后半部分稍有波动<br>Val acc   大体上不断增大，但后半部分稍有波动</p>
<p>以上说明网络正在学习，状态良好。<br><img src="https://imgbed.cheney.cc/picgo/b210ddc9555844f0b07c486f1bf02216.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p><img src="https://imgbed.cheney.cc/picgo/ff6d7640f4a242c5a9c3668fa7b61667.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p>然后输出识别出的花卉对应的标签以及名称：<br>第1朵花预测: Label: 0 bee<br>第2朵花预测: Label: 1 bLackberry<br>第3朵花预测: Label: 2 bLanket<br>第4朵花预测: Label: 3 bougainvillea<br>第5朵花预测: Label: 4 bromelia<br>第6朵花预测: Label: 5 foxgLove<br><img src="https://imgbed.cheney.cc/picgo/e957a9e3b89d4b5e8cc7d94dfd8db10f.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p>然后将图片和名称显示在一张图片内方便观察。<br><img src="https://imgbed.cheney.cc/picgo/9f8740bbe4fb48dfa9a20053bc8b8925.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/">人工智能</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/Python/">Python</a>
                    
                      <a class="hover-with-bg" href="/tags/Tensorflow/">Tensorflow</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2021/10/03/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD__%E5%9B%BE%E5%83%8F%E6%81%A2%E5%A4%8D(%E5%8A%A0%E5%99%AA%E4%B8%8E%E5%8E%BB%E5%99%AA)/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">图像恢复(加噪与去噪)</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2021/10/01/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD__%E6%96%91%E9%A9%AC%E9%97%AE%E9%A2%98%E5%A4%9A%E6%96%B9%E6%B3%95%E6%B1%82%E8%A7%A3/">
                        <span class="hidden-mobile">斑马问题多方法求解</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://cheney822.gitee.io/" target="_blank" rel="nofollow noopener"><span>备用网址</span></a> 
  </div>
  

  
  <!-- 备案信息 -->
  <div class="beian">
    <span>
      <a href="http://beian.miit.gov.cn/" target="_blank" rel="nofollow noopener">
        皖ICP备2022002876号-1
      </a>
    </span>
    
  </div>


  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/js/local-search.js" ></script>



  
    <script  src="/js/img-lazyload.js" ></script>
  



  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  






  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
        typing(title);
      
    })(window, document);
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>


</body>
</html>
